using Net8.Identity.Server.Extensions;
using Net8.Identity.Server.Services;

namespace Net8.Identity.Server
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            builder.Services.AddOpenIddictStartup(builder.Configuration, builder.Environment);
            builder.Services.AddScoped<AuthorizationService>();
            
            // 添加CORS服务
            builder.Services.AddCors();
            builder.Services.AddControllers();
            // 添加 Razor 运行时编译支持
            builder.Services.AddRazorPages().AddRazorRuntimeCompilation();
            // 注册迁移数据库
            builder.Services.AddScoped<IClientsSeeder, ClientsSeeder>();
            builder.Services.AddScoped<CorsSettingsService>();
            
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            var app = builder.Build();
            
            // 数据库迁移处理
            await app.UseMigrateDatabaseAsync();

            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
                // 异常页面中间件
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // 全局异常处理
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            // 中间件顺序优化（遵循官方推荐顺序）
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            
            // 配置CORS策略
            await app.UseCorsFromDatabaseAsync();
            
            app.UseAuthentication();
            app.UseAuthorization();

            // 添加控制器
            app.MapControllers();
            app.MapRazorPages();
            await app.RunAsync();
        }
    }
}